<template>
  <div class="login-container">
    <div class="login-card">
      <!-- logo图片 -->
       <div class="logo-box">
        <img src="/images/logo.jpg" alt="logo" />
      </div>

      <!-- 标题 -->
      <h2 class="login-title">宠物店管理系统</h2>

      <!-- 表单 -->
      <el-form
        :model="form"
        ref="loginForm"
        class="login-form"
        :rules="rules"
        label-width="0"
        @submit.prevent="onSubmit"
      >
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入账号"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="captcha">
          <el-row :gutter="10">
            <el-col :span="14">
              <el-input
                v-model="form.captcha"
                placeholder="请输入验证码"
                prefix-icon="el-icon-picture"
              ></el-input>
            </el-col>
            <el-col :span="10">
              <div class="captcha-box" @click="refreshCaptcha">
                {{ generatedCaptcha }}
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 记住我 + 注册 -->
        <el-form-item>
          <el-checkbox v-model="form.remember">记住我</el-checkbox>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <router-link to="/register" class="register-link">没有账号？点我注册</router-link> -->
        </el-form-item>

        <!-- 登录按钮 -->
         <div>
          <el-button
            type="primary"
            native-type="submit"
            class="login-btn"
            :loading="loading"
            @click="onSubmit"
            >登录</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { onMounted } from 'vue'

onMounted(() => {
  refreshCaptcha()
})

const router = useRouter()
//创建用户仓库
const userStore = useUserStore()

// 登录表单数据
const form = ref({
  username: '',
  password: '',
  captcha: '',
  remember: false,
})

const generatedCaptcha = ref('') // 你要先生成验证码再赋值
const loginForm = ref(null)
const loading = ref(false)

// 全局设置：不让非 2xx 状态码走 catch
axios.defaults.validateStatus = () => true

const refreshCaptcha = () => {
  //验证码刷新逻辑
  generatedCaptcha.value = generateRandomCaptcha() // 自定义生成函数
}

const onSubmit = () => {
  console.log('点击登录')
  loginForm.value.validate(async (valid) => {
    if (!valid) return

    // 验证码验证
    if (form.value.captcha.toUpperCase() !== generatedCaptcha.value.toUpperCase()) {
      ElMessage.error('验证码不正确')
      refreshCaptcha()
      return
    }

    loading.value = true

    try {
      const res = await axios.post('/api/auth/login', {
        username: form.value.username,
        password: form.value.password,
      })

      //登录成功
      if (res.status === 200 && res.data.success) {
        const userInfo = res.data.data // 假设这里包含 id, username, token, avatar
        console.log('登录成功，后端返回数据：', userInfo)

        userStore.setUserInfo(userInfo)

        // 本地存储
        if (form.value.remember) {
          localStorage.setItem('token', userInfo.token)
          localStorage.setItem('username', userInfo.username)
          localStorage.setItem('id', userInfo.id)
          localStorage.setItem('avatar', userInfo.avatar || '')
        } else {
          sessionStorage.setItem('token', userInfo.token)
          sessionStorage.setItem('username', userInfo.username)
        }
        

        ElMessage.success('登录成功')
        console.log('登录返回数据：', res.data)
        router.push('/home')
      } else {
        ElMessage.error(res.data.message || '登录失败')
        refreshCaptcha()
      }
    } catch (e) {
      console.error('发生错误：', e)
      ElMessage.error('网络异常')
      refreshCaptcha()
    } finally {
      loading.value = false
    }
  })
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

function generateRandomCaptcha(length = 4) {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  let code = ''
  for (let i = 0; i < length; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return code
}



</script>


<style scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-card {
  width: 400px;
  padding: 30px 40px;
  border: 1px solid #f44336;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center; /* 文本居中 */
}

.login-title {
  margin: 0;
  margin-bottom: 30px;
  font-size: 28px;
  color: #f44336;
  font-weight: bold;
}
.login-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-tabs {
  margin: 20px 0;
}
.captcha-box {
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #f5f5f5;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  user-select: none;
  cursor: pointer;
  font-weight: bold;
}
.register-link {
  float: right;
  font-size: 14px;
  color: #409eff;
}
.register-link:hover {
  text-decoration: underline;
}
.login-btn {
  width: 100%;
  height: 44px;
  border-radius: 22px;
  background: linear-gradient(90deg, #f44336, #d32f2f);
  border: none;
  font-size: 16px;
}
.login-footnote {
  margin-top: 20px;
  font-size: 12px;
  color: #999;
  text-align: center;
  line-height: 1.4;
}

.logo-box img{
  width: 250px;
  height: 200px;
}
</style>
